package com.chat.business;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;

import com.chat.data.MessageItem;
import com.chat.data.MessageType;
import com.chat.data.UserInfoBaseItem;
import com.chat.util.ChatConstants;

import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;

public class FriendListServiceImpl extends Thread {

    Random random = new Random();

    public static boolean blnRefreshList = false;

    @Override
    public void run() {
        this.setPriority(Thread.MIN_PRIORITY);
        MessageBroker broker = MessageBroker.getMessageBroker(null);
        // MessageService service = (MessageService) broker
        // .getService(ChatConstants.strMsgSrvce);

        while (true) {
            if (FriendListServiceImpl.blnRefreshList) {
                if (broker != null) {
                    Set<Long> setUserIDs = LoginActivity.mapUserIDQue.keySet();

                    for (Iterator<Long> iterator = setUserIDs.iterator(); iterator
                            .hasNext();) {
                        Long lngUserID = iterator.next();
                        String strMsgQueueId = LoginActivity.mapUserIDQue
                                .get(lngUserID);
                        List<UserInfoBaseItem> lstActiveUsers = new ArrayList<UserInfoBaseItem>(
                                LoginActivity.lstUserBaseInfo);

                        UserInfoBaseItem objUserInfoBaseItem = new UserInfoBaseItem(
                                lngUserID);
                        lstActiveUsers.remove(objUserInfoBaseItem);

                        String clientID = UUIDUtils.createUUID();
                        AsyncMessage msg = new AsyncMessage();
                        msg.setClientId(clientID);
                        msg.setMessageId(UUIDUtils.createUUID());
                        msg.setTimestamp(System.currentTimeMillis());
                        msg.setDestination(strMsgQueueId);

                        MessageItem objMessageItem = new MessageItem();
                        objMessageItem
                                .setStrMessageType(MessageType.FRIEND_LIST);
                        objMessageItem.getLstDataItems().addAll(lstActiveUsers);

                        msg.setBody(objMessageItem);

                        if (broker.getService(ChatConstants.MESSAGE_SERVICE)
                                .getDestination(strMsgQueueId) != null) {
                            broker.routeMessageToService(msg, null);
                        }
                        FriendListServiceImpl.blnRefreshList = false;
                    }
                } else {
                    broker = MessageBroker.getMessageBroker(null);
                }
            }
        }
    }
}
